#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>

int main()
{
    // 1. 创建并初始化文件
    int fd = open("test3.txt", O_RDWR | O_CREAT | O_TRUNC, 0644);
    write(fd, "LOCK_TEST", 9);
    lseek(fd, 0, SEEK_SET);

    struct flock lock = {
        .l_type = F_WRLCK,
        .l_whence = SEEK_SET,
        .l_start = 0,
        .l_len = 0 // 锁定整个文件
    };

    // 2. 加锁并fork子进程验证
    if (fcntl(fd, F_SETLK, &lock) == -1)
    {
        perror("Lock failed");
        exit(EXIT_FAILURE);
    }

    if (fork() == 0)
    { // 子进程尝试加锁
        printf("Child trying to acquire lock...\n");
        if (fcntl(fd, F_SETLK, &lock) == -1)
        {
            printf("Child lock failed (expected)\n");
        }
        exit(0);
    }

    sleep(2); // 确保子进程执行
    printf("Parent releasing lock...\n");
    lock.l_type = F_UNLCK;
    fcntl(fd, F_SETLK, &lock);
    wait(NULL);
    close(fd);
    return 0;
}